package com.ys.controller.web.business;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.ys.entity.purchase.TcgPurchaseByOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.ys.entity.business.TccPutaway;
import com.ys.entity.business.TpFbaBox;
import com.ys.entity.business.TpTimeCheck;
import com.ys.entity.sys.YsCol;
import com.ys.service.business.TpHolidaySetService;
import com.ys.service.business.TpTimeCheckService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService.UploadDto;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

@Controller
@RequestMapping("/web/business/tpTimeCheck")
public class WebTimeCheckController {

	private static Long MENU_ID = 47L;
	@Autowired
	private CommonApiService<TpTimeCheck> commonApiService;
	@Autowired
	private TpTimeCheckService tpTimeCheckService;
	@Autowired
	private TpHolidaySetService tpHolidaySetService;

	/*
	 * 获取时效考核数据
	 */
	@RequestMapping("/getTimeCheckList")
	@ResponseBody
	public LayuiTableVoJA getTimeCheckList(Model model, HttpServletRequest request, HttpServletResponse response,
										  //@ModelAttribute TpTimeCheck cond,
                                           String conditions
	){
		String countType = ConditionUtil.getConditionValue(conditions, "countTypeMsg");//状态
        String monthNum = ConditionUtil.getConditionValue(conditions, "monthNum");//月份
		String monthNumMin = "";
		String monthNumMax = "";
		if(countType == null){
			countType =  "-1";
		}
		if(monthNum == null){
			monthNumMin = getlastMonth();//获取上个月的日期信息
			monthNumMax = getlastMonth();
		}else {
			monthNumMin = monthNum.split("~")[0].trim();
			monthNumMax = monthNum.split("~")[1].trim();
		}

		List<Map<String, Object>>  resList = getTimeCheck(monthNumMin,monthNumMax,countType);//获取结果集
		LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resList));
		tableVoJA.setData(jsonArray);
		tableVoJA.setCode(0);

		return tableVoJA;
	}
	//获取结果集
	public List<Map<String, Object>>  getTimeCheck(String monthNumMin,String monthNumMax,String countType){
		//String oldMonthStr = getlastMonth();//获取上个月的日期信息
		//String oldMonthCh = oldMonthStr.split("-")[0] + "年" + oldMonthStr.split("-")[1] + "月";

		//结果集
		List<Map<String, Object>> resList = new ArrayList<>();
		List<Map<String, Object>> voList  = tpTimeCheckService.searchTimeCheck(monthNumMin,monthNumMax,Integer.parseInt(countType));

		if(voList!=null && voList.size()>0){
			for(int i=0;i<voList.size();i++){
				Map mapInfo = new HashMap();
				int infoCount = 0;
				int infoCycle = 0;
				int overNum = 0;
				if(voList.get(i).get("CountType").toString().equals("0")){//组装超时效
					infoCount = (int) voList.get(i).get("countNum");
					infoCycle = (int) voList.get(i).get("overCount");
					overNum = 2;
				}else if(voList.get(i).get("CountType").toString().equals("1")){//装箱超时效
					infoCount = (int) voList.get(i).get("countNum");
					infoCycle = (int) voList.get(i).get("overCount");
					overNum = 1;
				}else{//平均超时效周期
					infoCount = (int) voList.get(i).get("countNum");
					infoCycle = (int) voList.get(i).get("overCount");
					overNum = 2;
				}
				mapInfo.put("id",i);//标识
				mapInfo.put("countTypeMsg",voList.get(i).get("CountType").toString());//状态
				String oldMonthStr = voList.get(i).get("CountMonth").toString();
				String oldMonthCh = oldMonthStr.split("-")[0] + "年" + oldMonthStr.split("-")[1] + "月";
				mapInfo.put("monthNum",oldMonthCh);//月份
				mapInfo.put("count",infoCount);//数量
				mapInfo.put("overNum",overNum);//标准时效
				//平均超时效周期
				double infoAverage = (infoCount==0?0.00:infoCycle / infoCount);
				mapInfo.put("averageCycle",String.format("%.2f", infoAverage));
				resList.add(mapInfo);
			}
		}

		String lastMonthStr = getlastMonth();//获取上个月的日期信息
		String lastMonthCh = lastMonthStr.split("-")[0] + "年" + lastMonthStr.split("-")[1] + "月";
		//判断是否包含上个月
		int res1=lastMonthStr.compareTo(monthNumMin);
		int res2=lastMonthStr.compareTo(monthNumMax);
		if(res1>=0 && res2<=0 && monthNumMin.equals(monthNumMax) && countType.equals("-1")){
			if(resList==null || resList.size()<3){
				if(resList.size()<=0){
					for(int i=0;i<3;i++){
						Map mapInfo = new HashMap();
						mapInfo.put("id",i);//标识
						mapInfo.put("countTypeMsg",i);//状态
						mapInfo.put("monthNum",lastMonthCh);//月份
						mapInfo.put("count",0);//数量
						mapInfo.put("averageCycle",0.00);//平均超时效周期
						resList.add(mapInfo);
					}
				}else {
					List<Map<String, Object>> resListNew = new ArrayList<>();
					for(int i=0;i<3;i++){
						int hasDate = 0;
						Map mapInfo = new HashMap();
						for(int j=0;j<resList.size();j++){
							if(resList.get(j).get("countTypeMsg").equals(i+"")){
								mapInfo = resList.get(j);
								hasDate ++;
							}
						}
						if(hasDate != 0){
							resListNew.add(mapInfo);
						}else {
							mapInfo.put("id",i);//标识
							mapInfo.put("overNum",(i==1?1:2));//标准时效
							mapInfo.put("countTypeMsg",i);//状态
							mapInfo.put("monthNum",lastMonthCh);//月份
							mapInfo.put("count",0);//数量
							mapInfo.put("averageCycle",0.00);//平均超时效周期
							resListNew.add(mapInfo);
						}

					}
					return resListNew;
				}
			}
		}
		return resList;
	}

	//统计页面导出
	@RequestMapping("/exportCount")
	@ResponseBody
	public R exportCount(String conditions) throws Exception {
		String countType = ConditionUtil.getConditionValue(conditions, "countTypeMsg");//状态
		String monthNum = ConditionUtil.getConditionValue(conditions, "monthNum");//月份
		String monthNumMin = "";
		String monthNumMax = "";
		if(countType == null){
			countType =  "-1";
		}
		if(monthNum == null){
			monthNumMin = getlastMonth();//获取上个月的日期信息
			monthNumMax = getlastMonth();
		}else {
			monthNumMin = monthNum.split("~")[0].trim();
			monthNumMax = monthNum.split("~")[1].trim();
		}
		List<Map<String, Object>> resList =  getTimeCheck(monthNumMin,monthNumMax,countType);//获取结果集
		List<YsCol> listField = new ArrayList<>();
		listField.add(new YsCol().setName("状态").setCode("statusMsg"));
		listField.add(new YsCol().setName("标准时效").setCode("overNum"));
		listField.add(new YsCol().setName("月份").setCode("monthNum"));
		listField.add(new YsCol().setName("数量").setCode("count"));
		listField.add(new YsCol().setName("平均超时效周期").setCode("averageCycle"));

		ExportExcelUtils<TpTimeCheck> util = new ExportExcelUtils<TpTimeCheck>(new TpTimeCheck());
        
        String toFilePath = util.exportExcel(resList, listField, "时效考核表");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());

	}

	/*
	 * 详情页面
	 */
	@GetMapping("/toTimeCheckDetail")
	public String toTimeCheckDetail(Model model, HttpServletRequest request, HttpServletResponse response,
									   Long countTypeMsg,String monthNum,HttpSession session){

		session.setAttribute("toTimeCheckDetailId",countTypeMsg);
		session.setAttribute("toTimeCheckDetailMonthNum",monthNum);
		return "business/tpTimeCheck/tpTimeCheckDetails";
	}

	/*
	 * 获取时效考核数据
	 */
	@RequestMapping("/getTimeCheckDetailList")
	@ResponseBody
	public LayuiTableVoJA getTimeCheckDetailList(Model model, HttpServletRequest request, HttpServletResponse response,
										  @ModelAttribute TpTimeCheck cond,
										  String conditions,HttpSession session
	){

		long countTypeMsg = (long)session.getAttribute("toTimeCheckDetailId");
		String monthNum =  session.getAttribute("toTimeCheckDetailMonthNum").toString();
		cond = setCond(countTypeMsg,monthNum,cond);
		LayuiTableVoJA tableVoJA = commonApiService.searchLay(cond);

		return tableVoJA;
	}

	//详情页面导出
	@RequestMapping("/exportDetail")
	@ResponseBody
	public R exportDetail(@ModelAttribute TpTimeCheck cond, String conditions,HttpSession session) throws Exception {

		cond.setPage(0).setSize(999999);
		long countTypeMsg = (long)session.getAttribute("toTimeCheckDetailId");
		String monthNum =  session.getAttribute("toTimeCheckDetailMonthNum").toString();
		cond = setCond(countTypeMsg,monthNum,cond);
		List<Map<String, Object>> listData = cond.queryMap();
		List<YsCol> listField = new ArrayList<>();
		listField.add(new YsCol().setName("状态").setCode("infoType"));
		listField.add(new YsCol().setName("单号").setCode("code"));
		listField.add(new YsCol().setName("开始时间").setCode("beginTime"));
		listField.add(new YsCol().setName("结束时间").setCode("endTime"));
		listField.add(new YsCol().setName("超时天数").setCode("overDay"));
		listField.add(new YsCol().setName("运营公司简称").setCode("VGsJc"));
		listField.add(new YsCol().setName("运营公司编码").setCode("VGsBm"));
		listField.add(new YsCol().setName("运营人").setCode("UserName"));
		listField.add(new YsCol().setName("运营人账号").setCode("UserId"));
		listField.add(new YsCol().setName("运营人部门").setCode("DeptName"));

		ExportExcelUtils<TpTimeCheck> util = new ExportExcelUtils<TpTimeCheck>(new TpTimeCheck());
        
        String toFilePath = util.exportExcel(listData, listField, "超时效信息表");
        UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
        return R.ok(dto.getUrl());
	}

	public TpTimeCheck setCond(long countTypeMsg,String monthNum, TpTimeCheck cond){
		//String oldMonthStr = getlastMonth();//获取上个月的日期信息 yyyy年mm月
		String oldMonthStr = monthNum.substring(0, 4) + "-" + monthNum.substring(5, 7);
		if(countTypeMsg==0){//组装超时效
			cond.addField("'组装超时效' AS infoType");//状态
			//cond.addField("P.VGsJc");//运营公司简称
			//cond.addField("P.VGsBm");//运营公司编码
			cond.addField("C.VGsJc");//运营公司简称
			cond.addField("C.VGsBm");//运营公司编码
			cond.addField("U.UserId");//运营人账号
			cond.addField("U.UserName");//运营人姓名
			cond.addField("U.DeptName");//运营人部门
			cond.addLeftJoin("( SELECT MAX ( B.CreateTime ) AS CreateTime, B.Bid,B.ProductID,B.VGsJc,B.VGsBm FROM TCC_ProductAssemble B GROUP BY B.Bid,B.ProductID,B.VGsJc,B.VGsBm ) C ON A.Code = C.Bid ");
			cond.addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = C.VGsBm ");
			cond.addLeftJoin("TS_UserInfo U ON  U.UserId = O.CUser ");
		}else if(countTypeMsg==1){//装箱超时效
			cond.addField("'装箱超时效' AS infoType");//状态
			cond.addField("P.NameCompany VGsJc");//运营公司简称
			cond.addField("P.CodeCompany VGsBm");//运营公司编码
			cond.addField("U.UserId");//运营人账号
			cond.addField("U.UserName");//运营人姓名
			cond.addField("U.DeptName");//运营人部门
			cond.addLeftJoin("TP_FbaBox P ON P.Bid = A.Code ");
			cond.addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = P.CodeCompany ");
			cond.addLeftJoin("TS_UserInfo U ON  U.UserId = O.CUser ");
		}else {//采购超时效
			cond.addField("'采购超时效' AS infoType");//状态
			cond.addField("P.VGsJc");//运营公司简称
			cond.addField("P.VGsBm");//运营公司编码
			cond.addField("U.UserId");//运营人账号
			cond.addField("U.UserName");//运营人姓名
			cond.addField("U.DeptName");//运营人部门
			cond.addLeftJoin("TCG_PurchaseByOrder P ON P.Bid = A.Code ");
			cond.addLeftJoin("THR_OperateCompanyApply O ON O.VGsBm = P.vGsbm ");
			cond.addLeftJoin("TS_UserInfo U ON  U.UserId = O.CUser ");
		}

		cond.where("A.CountMonth = '"+oldMonthStr+"'");
		cond.where("A.CountType = "+countTypeMsg+"");
		return cond;
	}

	/*
	 *  重新统计数据页面
	 */
	@GetMapping("/toTimeCheckRefresh")
	public String toTimeCheckRefresh(Model model, HttpServletRequest request, HttpServletResponse response){

		return "business/tpTimeCheck/toTimeCheckRefresh";
	}


	/*
	 * 重新拉取统计数据
	 */
	@PostMapping("/reSetTimeCheckData")
	@ResponseBody
	public LayuiTableVoJA reSetTimeCheckData(Model model, HttpServletRequest request, HttpServletResponse response,
										   @RequestParam Map<String, Object> params
	){

		String chooseMonthMin = params.get("chooseMonthMin").toString();
		String chooseMonthMax = params.get("chooseMonthMax").toString();

		String endMonth = getNextMonth(chooseMonthMax);
		String beginMonth = chooseMonthMin;
		while (!beginMonth.equals(endMonth)){
			//次月
			String nextMonth = getNextMonth(beginMonth);
			//已经统计的先删除
			tpTimeCheckService.deleteTimeCheck(beginMonth);
			//再统计超时数据
			//统计组装超时数据
			countAssemble(beginMonth,nextMonth);
			//统计装箱超时数据
			countPacking(beginMonth,nextMonth);
			//统计采购超时数据
			countBuy(beginMonth,nextMonth);
			beginMonth = nextMonth;
		}

		LayuiTableVoJA tableVoJA = new LayuiTableVoJA();
		tableVoJA.setCode(0);
		return tableVoJA;
	}

	//获取下个月
	public String getNextMonth(String thisMonth){
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String nextMonth = "";
		try {
			Date startMonth = sdf.parse(thisMonth);
			Calendar cal = Calendar.getInstance();
			cal.setTime(startMonth);
			cal.add(Calendar.MONTH, +1);
			Date thatDate = cal.getTime();
			nextMonth = sdf.format(thatDate);

		} catch (ParseException e) {
			e.printStackTrace();
		}
		return nextMonth;
	}


	//获取上个月的日期信息
	public String getlastMonth(){
		//获取当前时间
		Calendar cal = Calendar.getInstance();
		Date date = new Date();//现在的日期
		cal.setTime(date);
		int year = cal.get(Calendar.YEAR);//获取年
		int month = cal.get(Calendar.MONTH)+1;//获取月（月份从0开始，如果按照中国的习惯，需要加一）
		//这个月
		//String thisMonthStr = year + "-" + (month<10 ? "0"+month : month);
		//上个月
		String oldMonthStr = "";
		if(month==1){
			oldMonthStr = (year-1) + "-12";
		}else {
			int oldMonth = month-1;
			oldMonthStr = year + "-" + (oldMonth<10 ? "0"+oldMonth : oldMonth);
		}
		return oldMonthStr;
	}
	//统计采购超时数据
	public void countBuy(String oldMonthStr,String thisMonthStr){
		//List<TcgPurchaseByOrder> buyList = new TcgPurchaseByOrder()
		List<Map<String,Object>> buyList = new TcgPurchaseByOrder()
				//.where("A.State = '已审核' ")
				.addField("P.UpdateTime AS theEndDate")
				.where("CONVERT(VARCHAR ,A.UpdateTime ,120) BETWEEN '"+oldMonthStr+"' AND '"+thisMonthStr+"'")
				.addLeftJoin("TCG_Payment P ON P.OrderID = A.Bid")
				.where("P.UpdateTime IS NOT NULL")
				.queryMap();
		if(buyList!=null && buyList.size()>0){
			for (int i=0;i<buyList.size();i++){
				Date start = (Date) buyList.get(i).get("createTime");// .getCreateTime();
				Date end = (Date) buyList.get(i).get("theEndDate");//.getUpdateTime();

				//获取超时的时间
				int overTime = tpHolidaySetService.checkOverTime(start,end,1)-2;
				//>=2时超时，存入
				if(overTime>0){
					Map<String, Object> tpTimeCheck = new HashMap<>();
					//存入
					tpTimeCheck.put("code",buyList.get(i).get("bid"));
					tpTimeCheck.put("beginTime",(Date) buyList.get(i).get("createTime"));
					tpTimeCheck.put("endTime",(Date) buyList.get(i).get("theEndDate"));
					tpTimeCheck.put("countType",2);
					tpTimeCheck.put("overDay",overTime);
					tpTimeCheck.put("countMonth",oldMonthStr);
					//新增
					tpTimeCheckService.add(tpTimeCheck);
				}
			}
		}
	}

	//统计装箱超时数据
	public void countPacking(String oldMonthStr,String thisMonthStr){
		List<TpFbaBox> packingList = new TpFbaBox()
				.where("A.State =2 ")
				.where("CONVERT(VARCHAR ,A.UpdateTime ,120) BETWEEN '"+oldMonthStr+"' AND '"+thisMonthStr+"'")
				.queryList();
		if(packingList!=null && packingList.size()>0){
			for (int i=0;i<packingList.size();i++){
				Date start = packingList.get(i).getCreateTime();
				Date end = packingList.get(i).getUpdateTime();

				//获取超时的时间
				int overTime = tpHolidaySetService.checkOverTime(start,end,1)-1;
				//>=1时超时，存入
				if(overTime>0){
					Map<String, Object> tpTimeCheck = new HashMap<>();
					//存入
					tpTimeCheck.put("code",packingList.get(i).getBid());
					tpTimeCheck.put("beginTime",packingList.get(i).getCreateTime());
					tpTimeCheck.put("endTime",packingList.get(i).getUpdateTime());
					tpTimeCheck.put("countType",1);
					tpTimeCheck.put("overDay",overTime);
					tpTimeCheck.put("countMonth",oldMonthStr);
					//新增
					tpTimeCheckService.add(tpTimeCheck);
				}
			}
		}
	}

	//统计组装超时数据
	public void countAssemble(String oldMonthStr,String thisMonthStr){
		List<Map<String,Object>> assembleList = new TccPutaway()
				.addField("C.Bid")
				.addField("C.CreateTime AS beginTime")
				.addLeftJoin("( SELECT MAX ( B.CreateTime ) AS CreateTime, B.Bid FROM TCC_ProductAssemble B GROUP BY B.Bid ) C ON A.AssembleID = C.Bid ")
				.where("A.EffectStock = 1")
				.where("CONVERT(VARCHAR ,A.UpdateTime ,120) BETWEEN '"+oldMonthStr+"' AND '"+thisMonthStr+"'")
				.queryMap();
		if(assembleList!=null && assembleList.size()>0){
			for (int i=0;i<assembleList.size();i++){
				Date start = (Date) assembleList.get(i).get("beginTime");
				Date end = (Date) assembleList.get(i).get("updateTime");

				//获取超时的时间
				int overTime = tpHolidaySetService.checkOverTime(start,end,1)-2;
				//>=2时超时，存入
				if(overTime>0){
					Map<String, Object> tpTimeCheck = new HashMap<>();
					//存入
					tpTimeCheck.put("code",assembleList.get(i).get("Bid").toString());
					tpTimeCheck.put("beginTime",(Date) assembleList.get(i).get("beginTime"));
					tpTimeCheck.put("endTime",(Date) assembleList.get(i).get("updateTime"));
					tpTimeCheck.put("countType",0);
					tpTimeCheck.put("overDay",overTime);
					tpTimeCheck.put("countMonth",oldMonthStr);
					//新增
					tpTimeCheckService.add(tpTimeCheck);
				}
			}
		}
	}



}



